
import { Button, Flex, Form, Input, message, Modal, Pagination, PaginationProps, Radio, RadioChangeEvent, Space, Table } from 'antd';
import style from '../css/Dictionarymanaged.module.scss'
import { TableProps } from 'antd/lib';
import { useEffect, useState } from 'react';
import { dictionarydetaildel, dictionarydetailinsert, dictionarydetaillists, dictionarydetailupdate, dictionarylists } from '../utils/request';
import moment from 'moment';
function dictionarymanaged() {
    const [form] = Form.useForm();
    interface DataType {
        key: string;
        code: string;
        name: string;
        status: string;
        updatetime: string;
        note: string;
        dictionarydetail_id:number
    }

    const columns: TableProps<DataType>['columns'] = [
        {
            title: '编码',
            dataIndex: 'code',
            key: 'code',
            width: '101px',
            render: (_, __, index) => '0' + (index + 1), // 序号从1开始
        },
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
            width: '185px'
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            width: '100px',
            render: (text) => (
                text == "启用" ?
                    <p><span style={{ display: 'inline-block', width: 10, height: 10, borderRadius: '50%', backgroundColor: 'rgba(24, 204, 208, 1)', marginRight: 5 }}></span>{text}</p>
                    :
                    <p><span style={{ display: 'inline-block', width: 10, height: 10, borderRadius: '50%', backgroundColor: 'rgba(236, 33, 33, 1)', marginRight: 5 }}></span>{text}</p>
            )
        },
        {
            title: '更新时间',
            key: 'updatetime',
            dataIndex: 'updatetime',
            width: '160px',
            render:(text) =><span>{moment(text).format("YYYY-MM-DD HH:mm:ss")}</span>,
        },
        {
            title: '备注',
            key: 'note',
            dataIndex: 'note',
            width: '147px'
        },
        {
            title: '操作',
            key: 'action',
            render: (_,record) => (
                <Space size="middle">     
                    <a onClick={() => edit(record)}>编辑</a>
                    <a style={{ color: '#EC2121' }} onClick={() => del(record.dictionarydetail_id)}>删除</a>
                </Space>
            ),
            width: 154
        },
    ];

    const [data,setData] = useState<DataType[]>([])
    const [mackDate,setMackdate] = useState([])
    useEffect(()=>{
        dictionarylists().then(res=>{
            setDictionarylist(res.data)
        }).catch(err=>{
            console.log(err)
        })
        dictionarydetaillists({
            id:1
        }).then(res=>{
            setData(res.data.slice(0,7))
            setMackdate(res.data)
        }).catch(err=>{
            console.log(err)
        })
    },[])
    // 字典详情分页器
    const onShowSizeChange: PaginationProps['onChange'] = (current, pageSize) => {
            console.log(current, pageSize);
            setCurrentPage(current)
            setData(mackDate.slice((current-1)*pageSize,current*pageSize))
        };
    // 字典列表
    const [dictionarylist,setDictionarylist] = useState([
        {
            dictionary:'',
            dictionary_id:1
        }
    ])
    // 字典列表点击选择
    const [selectID,setSelectID] = useState(1)
    const [select,setSelect] = useState(0)
    const [currentPage, setCurrentPage] = useState(1);
    const setselect=(i: number,id: number)=>{
        setSelect(i)
        setSelectID(id)
        dictionarydetaillists({
            id
        }).then(res=>{
            setData(res.data.slice(0,7))
            setMackdate(res.data)
            setCurrentPage(1)
        }).catch(err=>{
            console.log(err)
        })
    }
    // 新增
    const [module,setModule] = useState('新增')
    const [insertloading,setInsertloading] = useState(false)
    const [insertshow,setInsertshoe] = useState(false)
    const insert=()=>{
        console.log('新增')
        setInsertshoe(true)
        setModule('新增')
    }
    // 对话框关闭
    const insertCancel=()=>{
        console.log('取消')
        setInsertshoe(false)
        form.resetFields()
    }
    // 对话框确认
    const insertOk=()=>{
        console.log('确认')
        setInsertloading(true)
        setTimeout(() => {
            setInsertloading(false)
            form.validateFields().then(values => {
                console.log('Validated values: ', values);
                if(module=='新增'){
                    dictionarydetailinsert({
                        id:selectID,
                        ...values
                    }).then(res=>{
                        setData(res.data.slice(0,7))
                        setMackdate(res.data)
                        setCurrentPage(1)
                    }).catch(err=>{
                        console.log(err)
                    })
                }else{
                    dictionarydetailupdate({
                        id:selectID,
                        ...values,
                        dictionarydetail_id:test.dictionarydetail_id
                    }).then(res=>{
                        setData(res.data.slice(0,7))
                        setMackdate(res.data)   
                        setCurrentPage(1)
                    }).catch(err=>{
                        console.log(err)
                    })
                }
                form.resetFields()
                setInsertshoe(false)
            }).catch(info => {
                console.log('Validate Failed:', info);
            });
        }, 2000);
    }
    // 对话框单选
    const [value, setValue] = useState('启用');

    const onChange = (e: RadioChangeEvent) => {
        console.log('radio checked', e.target.value);
        setValue(e.target.value);
    };
    // 编辑
    const [test,setTest] = useState({
        dictionarydetail_id:1
    })
    const edit=(text:any)=>{
        console.log('编辑',text)
        setTest(text)
        form.setFieldsValue(text)
        setModule('编辑')
        setInsertshoe(true)
    }
    // 删除
    const [delloading,setDelloading] = useState(false)
    const [delshow,setDelshow] = useState(false)
    const [delId,setDelId] = useState(0)
    const del=(i: number)=>{
        console.log('删除')
        setDelId(i)
        setDelshow(true)
    }
    // 确认删除
    const confirmOk=()=>{
        console.log('确认删除')
        setDelloading(true)
        setTimeout(() => {
            dictionarydetaildel({
                dictionarydetail_id:delId,
                id:selectID
            }).then(res=>{
                console.log(res)
                setData(res.data.slice(0, 7))
                setMackdate(res.data)
                setDelloading(false)
                setDelshow(false)
                message.success(`删除操作成功！`);
                setCurrentPage(1)
            }).catch(err=>{
                console.log(err)
            })
            
        }, 2000);
    }
    // 取消删除
    const confirmCancel=()=>{
        console.log('取消删除')
        message.warning(`已取消操作！`);
        setDelshow(false)
    }
    // 字典列表输入框
    const getlists=(event: React.ChangeEvent<HTMLInputElement>)=>{
        console.log('字典列表:'+event.target.value) 
    }
    // 字典详情输入框
    const getdetails=(event: React.ChangeEvent<HTMLInputElement>)=>{
        console.log('字典详情:'+event.target.value)
    }
    return (
        <>
            {/* 新增对话框 */}
            <Modal
                title='新增字典'
                open={insertshow}
                width={750}
                onCancel={insertCancel}
                footer={[
                    <Flex key='flex' justify='flex-end'>
                        <Button key="back" onClick={insertCancel} style={{ height: 32, marginRight: 10 }}>
                            取消
                        </Button>,
                        <Button key="submit" type="primary" loading={insertloading} onClick={insertOk} style={{ height: 32 }}>
                            确认
                        </Button>,
                    </Flex>
                ]}
            >
                <Form
                    form={form}
                    initialValues={{status:value}}
                    style={{marginTop:30}}
                >
                    <Form.Item label='名称' name='name' rules={[{required:true}]} className={style.itemstyle}>
                        <Input placeholder='请输入'></Input>
                    </Form.Item>
                    <Form.Item label='启用状态' name='status' rules={[{required:true}]} className={style.itemstyle}>
                        <Radio.Group onChange={onChange}>
                            <Radio value={'启用'}>启用</Radio>
                            <Radio value={'禁用'}>禁用</Radio>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item label="备注" name='note' className={style.itemstyle}>
                        <Input.TextArea  style={{resize:'none',height:69}} placeholder='请输入' />
                    </Form.Item>
                </Form>
            </Modal>
            {/* 删除对话框 */}
            <Modal
                title={
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                        <img src="https://cdn7.axureshop.com/demo2024/2321849/images/%E5%8F%82%E6%95%B0%E9%85%8D%E7%BD%AE/u10369.svg" alt="" />
                        <span style={{ marginLeft: 5 }}>删除确认</span>
                    </div>
                }
                open={delshow}
                onOk={confirmOk} 
                onCancel={confirmCancel}
                footer={[
                    <Flex key='flex' justify='flex-end'>
                        <Button key="back" onClick={confirmCancel} style={{ height: 32, marginRight: 10 }}>
                            取消
                        </Button>,
                        <Button key="submit" type="primary" loading={delloading} onClick={confirmOk} style={{ height: 32 }}>
                            确认
                        </Button>,
                    </Flex>
                ]}
            >
                <p className={style.confirm}>是否继续操作删除时段操作？</p>
            </Modal>

            <div className={style.dictionarymanaged}>
                <div className={style.lists}>
                    <div className={style.title}>字典列表</div>
                    <div className={style.inputbox}>
                        <Input onInput={getlists} prefix={<img src='https://cdn7.axureshop.com/demo2024/2321849/images/%E9%97%A8%E8%AF%8A%E6%8C%82%E5%8F%B7/u3637.svg' />} placeholder='请输入...'></Input>
                    </div>
                    <ul className={style.dictionlists}>
                        {/* <li className={style.active}>关系</li>
                        <li>证件类型</li> */}
                        {
                             dictionarylist.map((item,index)=>(
                                <li key={index} onClick={()=>setselect(index,item.dictionary_id)} className={select==index?style.active:''}>{item.dictionary}</li>
                             ))
                        }
                    </ul>
                    <Pagination className={style.pagin} align='center' simple defaultCurrent={1} total={50} />
                </div>
                <div className={style.details}>
                    <div className={style.title}>字典详情</div>
                    <div className={style.datalists}>
                        <Flex justify='space-between'>
                            <Input onInput={getdetails} style={{ width: 208, height: 32 }} prefix={<img src='https://cdn7.axureshop.com/demo2024/2321849/images/%E9%97%A8%E8%AF%8A%E6%8C%82%E5%8F%B7/u3637.svg' />} placeholder='请输入...'></Input>

                            <Button onClick={()=>insert()} type="primary" style={{ width: 61, height: 32, borderRadius: 0 }}>新增</Button>
                        </Flex>
                        <Table<DataType> className={style.tabledata} columns={columns} rowKey='dictionarydetail_id' pagination={false} dataSource={data} />
                        <Pagination style={{ marginTop: 20 }} current={currentPage} onChange={onShowSizeChange} pageSize={7} total={mackDate.length} showSizeChanger={false} showTotal={(total) => `共 ${total} 条数据`} align="end" />
                    </div>
                </div>
            </div>
        </>
    );
}

export default dictionarymanaged;